package com.dagene.weixin.service;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.dagene.weixin.entity.WeixinUserInfo;
import com.dagene.weixin.repository.WeixinUserInfoDao;
import com.dagene.weixin.util.DateUtil;
import com.dagene.weixin.util.EmojiFilter;
import com.dagene.weixin.util.MediaUtil;

@Component
@Transactional(rollbackFor = Exception.class)
public class UserService {

	@Autowired
	WeixinUserInfoDao weixinUserInfoDao;

	public WeixinUserInfo getWeixinUserInfoByOpenId(String openid) {
		return weixinUserInfoDao.findByOpenid(openid);
	}

	/**
	 * 从微信端获取当前用户信息
	 * 
	 * @param weixin
	 * @return
	 * @throws Exception
	 */
	public WeixinUserInfo getWeixinUserInfo(String weixin) throws Exception {
		WeixinUserInfo info = weixinUserInfoDao.findByOpenid(weixin);
		if (info == null) {
			info = new WeixinUserInfo();
		}

		JSONObject jsonObj = MediaUtil.getUserInfo(weixin);
		System.out.println("saveuser:  " + weixin);
		if (jsonObj.has("errcode")) {
			if (40003 == jsonObj.getInt("errcode")) {
				throw new Exception("获取微信id出错，请先关注迪安诊断公众号。");
			} else {
				throw new Exception(jsonObj.getString("errmsg"));
			}
		}
		if (jsonObj.has("subscribe")
				&& jsonObj.getString("subscribe").equals("1")) {

			// "subscribe": 1, 关注
			// 用户的昵称
			String nickname = null;
			try {
				nickname = jsonObj.getString("nickname");

			} catch (Exception ex) {
			}
			// System.out.println("nickname："+jsonObj);
			nickname = EmojiFilter.filterEmoji(nickname);
			// 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
			// 用户头像 若用户更换头像，原有头像URL将失效。
			String headimgurl = null;
			try {
				headimgurl = jsonObj.getString("headimgurl");
			} catch (Exception ex) {
				// headimgurl =
				// "http://weixinzk.dazd.cn/zhuli/images/avstar2.jpg";
			}
			/* 保存微信信息 */
			info.setOpenid(weixin);
			info.setNickname(nickname);
			info.setHeadimgurl(headimgurl);
			info.setCity(jsonObj.getString("city"));
			info.setSex(jsonObj.getString("sex").toString().equals("1") ? "男"
					: "女");
			info.setSubscribetime(DateUtil.UnixTimeToDate(jsonObj
					.getString("subscribe_time")));
			info = weixinUserInfoDao.save(info);
			return info;
		} else {
			throw new Exception("您未关注迪安诊断微信号");
		}

	}

	public void saveWeixinUserInfo(WeixinUserInfo info) {
		weixinUserInfoDao.save(info);
	}

	public Page<WeixinUserInfo> queryUserByPage(Pageable page, String company) {
		if (StringUtils.isEmpty(company)) {
			return weixinUserInfoDao.findAll(page);
		} else {
			return weixinUserInfoDao.findByCompany(company, page);
		}
	}
}
